package code;

import EXtension.Controller.StartPanelController;

import EXtension.Util.FilterImageFIle;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.event.EventHandler;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import java.io.File;
import java.io.IOException;

public class AppLaunch extends Application {
    ThumbnailsArea thumbnailsArea=new ThumbnailsArea();
    @Override
    public void start(Stage PrimaryStage) throws IOException {
        AnchorPane ap=new AnchorPane();
        FolderPane folderPane=new FolderPane();
        TreeView<File> folderTree=folderPane.getFolderTree();

        FXMLLoader loader=new FXMLLoader(getClass().getResource("../StartPane.fxml"));
        Parent root =loader.load();
        root.getStylesheets().add(getClass().getResource("../Default.css").toExternalForm());

        StartPanelController startPanelController=loader.getController();

        startPanelController.getDirectoryTree().setCenter(folderPane);

        folderTree.getSelectionModel().selectedItemProperty().addListener(new ChangeListener<TreeItem<File>>() {

            @Override
            public void changed(ObservableValue<? extends TreeItem<File>> observable, TreeItem<File> oldValue,
                                TreeItem<File> newValue) {
                if (newValue == null) {
                    return;
                }
                try {
                    thumbnailsArea.loadThumbnails(FilterImageFIle
                            .getImage(newValue.getValue())
                    );
                    startPanelController.getThumbnailDisplay().setCenter(thumbnailsArea);

                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });


        ap.getChildren().add(root);
        AnchorPane.setBottomAnchor(root,0.0);
        AnchorPane.setLeftAnchor(root,0.0);
        AnchorPane.setTopAnchor(root,0.0);
        AnchorPane.setRightAnchor(root,0.0);


        PrimaryStage.setTitle("Image");
        PrimaryStage.setScene(new Scene(ap, 800, 450));
        PrimaryStage.show();
        PrimaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent windowEvent) {
                if(!thumbnailsArea.task.isCancelled()||!thumbnailsArea.executor.isShutdown()){
                    thumbnailsArea.task.cancel();
                    thumbnailsArea.executor.shutdown();
                    Platform.exit();
                }
            }
        });
    }

    public static void main(String[] args) {
        launch();
    }
}